﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Silent.Data.Converters
{
    public static class ConvertionService
    {
        private static readonly List<object> converters = new List<object>();

        public static void Register<T, U>(IConvertable<T, U> converter) where U : new()
        {
            converters.Add(converter);
        }
        public static U Convert<T, U>(T source) where U : new()
        {
            try
            {
                var converter = converters.FirstOrDefault(x => x is IConvertable<T, U>) as IConvertable<T, U>;
                return converter != null
                           ? converter.Convert(source)
                           : new DefaultConverter<T, U>().Convert(source);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return default(U);
            }
        }
    }
}